

[CmdletBinding(PositionalBinding=$false)]
Param(
  [Parameter(Mandatory)]
  $TargetIP,
  [Parameter(Mandatory)]
  $TargetUser,
  [Parameter(Mandatory)]
  $TargetGDBServerPort,
  [Parameter(Mandatory)]
  $TargetSSHServerPort,
  [Parameter(Mandatory)]
  $ExecPathLocal,
  [Parameter(Mandatory)]
  $ExecPathRemote
)

$SSHArgs="-o StrictHostKeyChecking=no "

if($TargetSSHServerPort.length -gt 0){
  $SSHArgs=$SSHArgs+"-P ${TargetSSHServerPort} "
}

$SSHArgArr=("${SSHArgs}${TargetUser}@${TargetIP}" -split ' ')

$ExecName=Split-Path ${ExecPathRemote} -Leaf


ssh ${SSHArgArr} "killall ${ExecName}"
ssh ${SSHArgArr} "ProcPID=`$(ss -tlnp | grep LISTEN | grep ${TargetGDBServerPort} | sed -n 's/.*pid=\([0-9]\+\).*/\1/p') && if [[ \`"`$ProcPID\`" != \`"\`" ]]; then echo kill `$ProcPID;kill `$ProcPID; else echo no process Port: ${TargetGDBServerPort}; fi"

scp ("${SSHArgs}${ExecPathLocal}" -split ' ') "${TargetUser}@${TargetIP}:${ExecPathRemote}"
if($LASTEXITCODE -ne 0){
  exit 2
}

ssh ${SSHArgArr} "chmod +x ${ExecPathRemote}"
if($LASTEXITCODE -ne 0){
  exit 3
}

